package com.lear.njava.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lear.njava.mapper.AdminMapper;
import com.lear.njava.pojo.Admin;
import com.lear.njava.pojo.LoginForm;
import com.lear.njava.service.AdminService;
import com.lear.njava.util.MD5;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("adminServiceImpl") // 加上service让spring识别当前组件，spring进行初始化，指定实现类的id
@Transactional // 进行事务控制
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Override
    public Admin login(LoginForm loginForm) {
        // 创建QueryWrapper对象
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>();
        // 拼接查询条件
        queryWrapper.eq("name", loginForm.getUsername());
        // 转换成密文进行查询
        queryWrapper.eq("password", MD5.encrypt(loginForm.getPassword()));
        Admin admin = baseMapper.selectOne(queryWrapper);
        return admin;
    } // 实现AdminService，继承ServiceImpl实现类，将用到的mapper/AdminMapper和实现类/Admin写入泛型

    @Override
    public Admin getAdminById(Long userId) {
        // 创建QueryWrapper对象
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>();
        // 查询条件，id等于传过来的id
        queryWrapper.eq("id", userId);
        Admin admin = baseMapper.selectOne(queryWrapper);
        return admin;
    }

    @Override
    public IPage<Admin> getAdminsByOpr(Page<Admin> pageParam, String adminName) {
        // 创建QueryWrapper查询包裹对象
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>();
        // 判断查询条件是否为空
        if (!StringUtils.isEmpty(adminName)) {
            // 拼接查询条件
            queryWrapper.like("name", adminName);
        }
        queryWrapper.orderByDesc("id");
        // 通过baseMapper进行查询
        Page<Admin> page = baseMapper.selectPage(pageParam, queryWrapper);
        return page;
    }
}
